"""
The class defines sidebar in the settings dialogue
"""
from common.settings import Settings
from common.utils.NovishLogger import logger

if Settings.FLAG_USE_PYQT:
    from PyQt5 import QtWidgets
    from PyQt5.QtGui import QFont
    from PyQt5.QtWidgets import QApplication, QStyleFactory
else:
    from PySide2 import QtWidgets
    from PySide2.QtGui import QFont
    from PySide2.QtWidgets import QApplication, QStyleFactory

SUB_ITEM_KEY = "sub_item"
TEXT_KEY = "text"
EXAMPLE_CONTENT_DICT = {"general": {TEXT_KEY: "通用"},
                        "detection": {TEXT_KEY: "检测"},
                        "standard": {TEXT_KEY: "标定"},
                        "hardware": {TEXT_KEY: "硬件", SUB_ITEM_KEY: {"camera": {TEXT_KEY: "相机"}}}}


class TreeItem(QtWidgets.QTreeWidgetItem):
    def __init__(self, resource_key):
        QtWidgets.QTreeWidgetItem.__init__(self)
        self._resource_key = resource_key

    @property
    def resource_key(self):
        return self._resource_key

    @resource_key.setter
    def resource_key(self, value):
        self._resource_key = value


class Sidebar(QtWidgets.QTreeWidget):
    def __init__(self, _settings_content_dict=EXAMPLE_CONTENT_DICT, sidbar_clicked_func=None, parent=None):
        QtWidgets.QTreeWidget.__init__(self)
        self.parent = parent
        self.__field_prefix = "tree_item_"
        self._settings_content_dict = _settings_content_dict
        self.headerItem().setHidden(True)
        self.setup_sidebar()
        self.setup_style()
        if sidbar_clicked_func:
            self.setup_connection(sidbar_clicked_func)

    def setup_sidebar(self):
        """
        Set up sidebar according to _settings_content_dict.
        @return:
        """
        i = 0
        for key, value in self._settings_content_dict.items():
            self.generate_main_item(key, value[TEXT_KEY])
            children_names = value[SUB_ITEM_KEY] if SUB_ITEM_KEY in value else {}
            for c_key, c_value in children_names.items():
                self.generate_sub_item(c_key, c_value[TEXT_KEY], key)
            i += 1
        if i:
            self.setCurrentItem(self.topLevelItem(i))
        self.setFixedWidth(150)

    def setup_style(self):
        """
        Set up style.
        @return:
        """
        self.setStyle(QStyleFactory.create('fusion'))

    def setup_connection(self, func=None):
        """
        Set up events.
        @return:
        """
        try:
            self.itemClicked.connect(func)
        except TypeError as e:
            logger.error(f"{e}")

    def generate_main_item(self, var, txt):
        """
        Generate main item
        @param var: attribute name, which will be used as a field for the class
        @param txt: show text on the UI
        @return:
        """
        item_name = f"{self.__field_prefix}{var}"
        # logger.debug(f"item_name:{item_name}")
        item_obj = TreeItem(item_name)
        setattr(self, item_name, item_obj)
        self.addTopLevelItem(item_obj)
        item_obj.setText(0, txt)

        font = QFont()
        font.setBold(True)
        font.setPointSize(15)
        item_obj.setFont(0, font)

    def generate_sub_item(self, var, txt, parent):
        """
        Generate sub item
        @param var: attribute name, which will be used as a field for the class
        @param txt: show text on the UI
        @param parent: parent
        @return:
        """
        item_name = f"{self.__field_prefix}{parent}_{var}"
        parent = f"{self.__field_prefix}{parent}"
        item_obj = TreeItem(item_name)
        setattr(self, item_name, item_obj)

        parent_tree_item = self.__dict__[parent]
        parent_tree_item.addChild(item_obj)
        item_obj.setText(0, txt)
        font = QFont()
        font.setBold(True)
        font.setPointSize(12)
        item_obj.setFont(0, font)


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    a = Sidebar()
    print(a.topLevelItemCount())
    for i in range(10):
        if a.topLevelItem(i):
            print(i, a.topLevelItem(i).text(0))
    # print(a.topLevelItem(2).text(0))
    # print(a.topLevelItem(2).__hash__())
    try:
        a.show()

        print(a.tree_item_detection.text(0))
    except Exception as e:
        print(e)
    app.exec_()
